#include "EffectManager.h"
#include "XML\XMLTreeNode.h"
#include "Logger\Logger.h"

#if defined (_DEBUG)
#include "Memory/MemLeaks.h"
#endif

//-------------------------------------------------
CEffectManager::CEffectManager()
	: m_WorldMatrix(m44fIDENTITY)
	, m_ViewMatrix(m44fIDENTITY)
	, m_2DViewMatrix(m44fIDENTITY)
	, m_ProjectionMatrix(m44fIDENTITY)
	, m_OrthographicMatrix(m44fIDENTITY)
	, m_ViewProjectionMatrix(m44fIDENTITY)
{
	m_2DViewMatrix.m23 = 1.f; // Set 1 for 2D rendering
}

//-------------------------------------------------
CEffectManager::~CEffectManager()
{
	CleanUp();
}

//-------------------------------------------------
void CEffectManager::CleanUp()
{
	m_EffectMap.Destroy();
	m_EffectTechniqueMap.Destroy();
}

//-------------------------------------------------
bool CEffectManager::Load(const std::string& _sFilename)
{
	m_sFilename = _sFilename;
	return LoadFile();
}

//-------------------------------------------------
bool CEffectManager::Reload()
{
	CleanUp();
	return LoadFile();
}

//-------------------------------------------------
bool CEffectManager::LoadFile()
{
	CXMLTreeNode newFile;
	if ( !newFile.LoadFile(m_sFilename.c_str()) )
	{
		std::string msg_error = "CEffectManager::Load->Error reading the effects file: " + m_sFilename;
		LOGGER->AddNewLog(ELL_ERROR, msg_error.c_str());
		return false;
	}

	CXMLTreeNode l_Effects = newFile["effects"];
	if (l_Effects.Exists())
	{
		uint16 l_Count = l_Effects.GetNumChildren();
		for(uint16 i=0; i < l_Count; ++i)
		{
			std::string l_Type = l_Effects(i).GetName();

			if(l_Type == "effect")
			{
				CEffect* l_pEffect = new CEffect( l_Effects(i) );
				l_pEffect->Load();

				std::string l_sName = l_pEffect->GetEffectName();
				m_EffectMap.AddResource(l_sName, l_pEffect);
			}
			else if(l_Type == "technique")
			{
				CEffectTechnique* l_pTechnique = new CEffectTechnique(l_Effects(i));
				std::string l_sTechniqueName = l_pTechnique->GetTechniqueName();

				m_EffectTechniqueMap.AddResource(l_sTechniqueName, l_pTechnique);
			}
		}
	}

	return true;
}

//-------------------------------------------------
CEffect* CEffectManager::GetEffect(const std::string& _sName)
{
	return m_EffectMap.GetResource(_sName);
}

//-------------------------------------------------
CEffectTechnique* CEffectManager::GetTechnique(const std::string& _sName)
{
	return m_EffectTechniqueMap.GetResource(_sName);
}

//-------------------------------------------------
void CEffectManager::SetCamera(const Mat44f& _view, const Mat44f& _projection)
{
	m_ViewMatrix			= _view;
	m_ProjectionMatrix		= _projection;
	m_ViewProjectionMatrix = _projection * _view;
}